package openbang.chatroom.web.client;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import openbang.chatroom.service.intf.ChatService;
import openbang.chatroom.service.vo.ChatGroup;
import openbang.chatroom.service.vo.ChatMsg;
import openbang.chatroom.web.widget.DateGwtHelper;
import openbang.chatroom.web.widget.text.RichTextToolbar;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratedStackPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * 
 * 显示聊天室控制台
 * 
 * 显示聊天室所有参与者
 * 显示聊天内容 --- 有滚动条的 HTML组件
 * 录入消息信息富文本框  -- RichTextArea
 * 
 * @author aibozeng
 *
 */

public class ChatRoomNow implements EntryPoint {
	//ROOT  左右两部分
	HorizontalPanel vRootPanel = new HorizontalPanel();
	
	//左边: 聊天信息(信息显示和信息录入)
	VerticalPanel vMsgPanel = new VerticalPanel();
	//TextArea  viewMsg = new TextArea();
	ScrollPanel viewMsgScroll = new ScrollPanel();
	VerticalPanel viewMsg = new VerticalPanel();
	Grid entryGrid = new Grid(2,1);
	RichTextToolbar entryMsgToolbar = null;
	RichTextArea  entryMsg = null; 
	HorizontalPanel vBtnPanel = new HorizontalPanel();
	Button    entryBtn = new Button("发送");
    
	//右边：工具面板 显示群信息、参与人等
	VerticalPanel vToolPanel = new VerticalPanel();
	
	//右边：工具面板的顶部基本信息  登录后的用户的基本信息--暂无
	HorizontalPanel vTopPanel = new HorizontalPanel();
    Button    quitBtn = new Button("退出");
	//聊天面板
	DecoratedStackPanel stackPanel = new DecoratedStackPanel();

	//以聊天室主题为根,参与者为叶子的树
	Tree participantTree = new Tree();
	//TreeItem rootItem = null; //下面可以挂多个聊天室
	TreeItem groupItem = null;
	
	//树放在一个可滚动的窗口里
	ScrollPanel scrollPanel = new ScrollPanel(participantTree);
	
	//当前消息最大的 token --- 本页面，只能处理一个聊天室
	String token = "0";
	ChatGroup chatGroup = null;
	
	//定时器一个  5秒取一次消息, 10秒取一次参与者
	ParticipantsTimer participantsTimer = null; 
	int participantsDelayMillis = 1000*10 ;//5秒
	NewMsgTimer newMsgTimer = null; 
	int newMsgDelayMillis = 1000*5 ;//5秒
	
	@Override
	public void onModuleLoad() {
		RootPanel.get("chatroomnow_div").add(vRootPanel);
		vRootPanel.add(vMsgPanel);
		vRootPanel.add(vToolPanel);
		vRootPanel.setSize("100%","501px");
		//vRootPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		//vRootPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		vRootPanel.setBorderWidth(1);
		vRootPanel.setCellHorizontalAlignment(vToolPanel, HasHorizontalAlignment.ALIGN_LEFT);
		
		vMsgPanel.add(viewMsgScroll);
		viewMsgScroll.setStyleName("openbang-RichText");
		viewMsgScroll.add(viewMsg);		
		entryMsg = new RichTextArea();
		entryMsgToolbar = new RichTextToolbar(entryMsg);
		entryGrid.setStyleName("openbang-RichText");
		entryGrid.setWidget(0,0,entryMsgToolbar);
		entryGrid.setWidget(1,0,entryMsg);
		vMsgPanel.add(entryGrid);
		vMsgPanel.add(vBtnPanel);
		vMsgPanel.setSize("600px","500px");
		//viewMsg.setReadOnly(true);
		viewMsgScroll.setSize("600px","300px");
		//viewMsg.setVisibleLines(30);
		entryMsgToolbar.setWidth("100%");
		entryMsg.setSize("600px","80px");
		//entryMsg.setVisibleLines(8);
		
		vBtnPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		vBtnPanel.add(entryBtn);
		vBtnPanel.add(new HTML("&nbsp;&nbsp;快捷键  &lt;Ctrl&gt;+&lt;Enter&gt;也可以发送消息"));
		
		vToolPanel.add(vTopPanel);
		vToolPanel.add(stackPanel);
		vToolPanel.setSize("200px","100%");
		
		vTopPanel.add(new HTML("欢迎您:"+getNiceNameInHtml()));
		vTopPanel.add(quitBtn);
		vTopPanel.setSize("100%","100%");
		vTopPanel.setCellHorizontalAlignment(quitBtn, HasHorizontalAlignment.ALIGN_RIGHT);
		
		scrollPanel.setPixelSize(190,380);
		stackPanel.add(scrollPanel, getHeaderString("参与者列表",null), true);
		participantTree.setAnimationEnabled(true);
		
		//rootItem = participantTree.addItem("当前参与的聊天室");
		
		initGroupData();		

		Window.addCloseHandler(new CloseHandler<Window>(){
			@Override
			public void onClose(CloseEvent<Window> event) {
				quitChatGroup();
		    }
		});
		
		entryMsg.addKeyPressHandler(new KeyPressHandler(){
			@Override
			public void onKeyPress(KeyPressEvent event) {
				//GWT.log("event.getCharCode()="+event.getNativeEvent().getKeyCode()); IE是10，FireFox是13
				//GWT.log("event.isControlKeyDown()="+event.isControlKeyDown());
				if(event.isControlKeyDown()&&(event.getNativeEvent().getKeyCode()==10||event.getNativeEvent().getKeyCode()==13)){
					entryBtn.click();
					//GWT.log("hi");
				}
			}
		});
	}
	
	public void quitChatGroup(){
		ChatService.Util.getInstance().quitGroup(getChatGroupIdInHtml(), getNiceNameInHtml(), new AsyncCallback<Integer>(){
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			}
			public void onSuccess(Integer result) {
				Window.Location.replace("http://www.openbang.net");
			}
		});		
	}
	
	/**
	 * 取群基本信息  一次
	 */
	public void initGroupData(){
		ChatService.Util.getInstance().getChatGroup(getChatGroupIdInHtml(),new AsyncCallback<ChatGroup>(){
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			}
			public void onSuccess(ChatGroup result) {
				if(result==null){
					return;
				}
				chatGroup = result;
				//隐藏进度条
				RootPanel.get("loading").setVisible(false);
				groupItem = participantTree.addItem("主题:"+result.getSubject());
				//触发定时器
				participantsTimer = new ParticipantsTimer();
				participantsTimer.schedule(participantsDelayMillis);

				newMsgTimer = new NewMsgTimer();
				newMsgTimer.schedule(newMsgDelayMillis);
				
				entryBtn.addClickHandler(new ClickHandler(){
					@Override
					public void onClick(ClickEvent event) {
						sendNewMsg();
					}
				});
				quitBtn.addClickHandler(new ClickHandler(){
					@Override
					public void onClick(ClickEvent event) {
						if(Window.confirm("你确认要退出当前聊天室吗?")){
							quitChatGroup();							
						}
					}
				});
				
				result = null;
			}
		});
	}
	
	private void sendNewMsg(){
		if(entryMsg.getText()==null || entryMsg.getText().trim().length()<=0){
			Window.alert("录入为空,不能发送.");
			return;
		}
		String newStr = entryMsg.getHTML().trim();
		viewMsg.add(new HTML(DateGwtHelper.format(new Date())+" 您说:<br>"+newStr+"<br>"));
		viewMsgScroll.scrollToBottom();
		ChatService.Util.getInstance().sendMsg(chatGroup.getGroupId(),getNiceNameInHtml(),newStr , new AsyncCallback<Integer>(){
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			}
			public void onSuccess(Integer result) {
				entryMsg.setText("");
				entryMsg.setFocus(true);
			}
		});
	}

	/**
	 * 定时取 聊天者信息
	 */
	public void updateParticipantsData(){
		ChatService.Util.getInstance().getParticipants(chatGroup.getGroupId(),new AsyncCallback<Set<String>>(){
			public void onFailure(Throwable caught) {				
				Window.alert(caught.getMessage());
				participantsTimer.schedule(participantsDelayMillis);
			}
			public void onSuccess(Set<String> result) {
				participantsTimer.schedule(participantsDelayMillis);
				if(result==null){
					return;
				}
				//把参与者树重新构造
				if(groupItem!=null){
					groupItem.removeItems();
					Iterator<String> iterator = result.iterator();
					while(iterator.hasNext()){
						groupItem.addItem(iterator.next());
					}
					groupItem.setState(true);
				}
				else{
					//Window.alert("groupItem is null");
				}
			}
		});
	}	

	/**
	 * 定时取 新消息
	 */
	public void updateNewMsgData(){
		ChatService.Util.getInstance().getNewChatMsg(chatGroup.getGroupId(), token, getNiceNameInHtml(), new AsyncCallback<List<ChatMsg>>(){
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
				newMsgTimer.schedule(newMsgDelayMillis);
			}
			public void onSuccess(List<ChatMsg> result) {
				if(result==null || result.size()<=0){
					newMsgTimer.schedule(newMsgDelayMillis);
					return;
				}
				//累加消息消息框里
				String newMsgStr = "";
				for(int i=0;i<result.size();i++){
					ChatMsg msg = result.get(i);					
					newMsgStr = newMsgStr + toViewOneMsg(msg)+"<br>";
					//记录当前最大消息Token
					token = msg.getToken();
				}
				viewMsg.add(new HTML(newMsgStr));
				viewMsgScroll.scrollToBottom();
				newMsgTimer.schedule(newMsgDelayMillis);
			}
		});
	}	
	
	private String toViewOneMsg(ChatMsg msg){
		return DateGwtHelper.format(msg.getSendDate())+" "+msg.getSender()+":<br>"+msg.getMsg();
	}
	
	private String getHeaderString(String text, String imageUrl) {
	    // Add the image and text to a horizontal panel
	    HorizontalPanel hPanel = new HorizontalPanel();
	    hPanel.setSpacing(0);
	    hPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
	    if(imageUrl!=null){
	       hPanel.add(new Image(imageUrl));
	    }
	    HTML headerText = new HTML(text);
	    headerText.setStyleName("openbang-StackPanelHeader");
	    hPanel.add(headerText);
	    // Return the HTML string for the panel
	    return hPanel.getElement().getString();
	}
	//获取 在 JSP的 javascript中定义的 group id
	public static native String getChatGroupIdInHtml() /*-{  
         return parent.getChatGroupId();
    }-*/;	
	public static native String getNiceNameInHtml() /*-{  
         return parent.getNiceName();
    }-*/;	
	
	private class ParticipantsTimer extends Timer{
		@Override
		public void run() {
			updateParticipantsData();
		}
	}

	private class NewMsgTimer extends Timer{
		@Override
		public void run() {
			updateNewMsgData();
		}
	}
	
}
